package flexconsole.controller {
	import flash.net.LocalConnection;
	
	import flexconsole.AppFacade;
	import flexconsole.ConfigKeys;
	import flexconsole.model.ICategoryProxy;
	import flexconsole.model.IConfigProxy;
	import flexconsole.model.ILogMessageProxy;
	import flexconsole.utils.LogXMLUtil;
	
	import flexunit.framework.Assert;
	
	import mx.logging.ILogger;
	import mx.logging.Log;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.command.SimpleCommand;
	
	/**
	 * Startup command for the application.
	 * @author ivanchoo
	 *
	 */
	public class ConnectionCommand extends SimpleCommand {
		
		static private var logger:ILogger = Log.getLogger("flexconsole.controller.ConnectionCommand");
		
		static private var _localConnection:LocalConnection;
		
		static private var isConnected:Boolean = false;
		
		override public function execute(notification:INotification):void {
			logger.debug("execute({0})", notification);
			super.execute(notification);
			
			//   Shutdown sequence
			try {
				var appFacade:AppFacade = facade as AppFacade;
				var connectionName:String = appFacade.configProxy.getValue(ConfigKeys.CONNECTION_NAME, "_mdbtrace");
				
				if (notification.getBody() === true) {
					connect(connectionName);
				} else {
					disconnect();
				}
				appFacade.configProxy.setValue(ConfigKeys.CONNECTED, isConnected);
			} catch (e:Error) {
				logger.error(e.message);
			}
		}
		
		public function trace(str:String):void {
			Assert.assertNotNull(str);
			var appFacade:AppFacade = facade as AppFacade;
			var xml:XML = LogXMLUtil.toXML(str);
			var category:String = appFacade.logMessageProxy.category(xml);
			var categoryProxy:ICategoryProxy = appFacade.categoryProxy;
			var logMessageProxy:ILogMessageProxy = appFacade.logMessageProxy;
			var configProxy:IConfigProxy = appFacade.configProxy;
			var maxLogNum:int = configProxy.getValue(ConfigKeys.MAX_LOG_NUM, 1000);
			logMessageProxy.add(xml);
			var i:int = logMessageProxy.collection.length - maxLogNum;
			
			if (i > 0) {
				while (i--) {
					logMessageProxy.collection.removeItemAt(0);
				}
			}
			
			if (!categoryProxy.find(category)) {
				categoryProxy.add(category);
			}
		}
		
		protected function connect(connectionName:String):void {
			Assert.assertNotNull(connectionName);
			logger.debug("connect({0})", connectionName);
			
			if (isConnected) {
				return;
			}
			localConnection.connect(connectionName);
			isConnected = true;
		}
		
		protected function disconnect():void {
			logger.debug("disconnect()");
			
			try {
				localConnection.close();
			} catch (e:Error) {
				logger.debug("disconnect() throws error but was ignored: {0}", e.message);
					//  ignore
			}
			isConnected = false;
		}
		
		protected function get localConnection():LocalConnection {
			if (_localConnection == null) {
				_localConnection = new LocalConnection();
				_localConnection.allowDomain('*');
				_localConnection.allowInsecureDomain();
				_localConnection.client = this;
			}
			return _localConnection;
		}
	}
}